package cn.com.fuhuitong.main.access.ui.activity

import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.access.ui.fragment.AccessAccountFragment
import cn.com.fuhuitong.main.access.vm.AccessViewModel
import cn.com.fuhuitong.main.base.ViewModeActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPStaticUtils
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.base.ActivityCollector
import cn.com.fuhuitong.entity.AccessAction
import cn.com.fuhuitong.entity.AuthResult
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.main.access.ui.fragment.AccessChangeFragment
import cn.com.fuhuitong.main.access.ui.fragment.AccessWeChatFragment
import cn.com.fuhuitong.popup.ConfirmCancelPopup
import cn.com.fuhuitong.popup.WebViewPopup
import cn.com.fuhuitong.utils.JsonUtils
import cn.com.fuhuitong.utils.WebViewUtils
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_web_view.*
import kotlinx.android.synthetic.main.fragment_access_account.*
import kotlinx.android.synthetic.main.fragment_access_change.*
import kotlinx.android.synthetic.main.fragment_access_mobile.*
import kotlinx.android.synthetic.main.fragment_access_register.*
import kotlinx.android.synthetic.main.fragment_access_wechat.*
import java.util.concurrent.TimeUnit

@Route(path = ARouteConstance.ACTIVITY_URL_ACCESS)
class AccessActivity : ViewModeActivity<AccessViewModel>() {

    private var accessAction: AccessAction? = null

    override fun viewModel(): AccessViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_access


    private val webViewPopup: WebViewPopup by lazy {
        WebViewPopup(
            context = this, onConfirm = {
                webViewPopup.dismiss()
                check_account_select.isChecked = true
            }, onCancel = {
                webViewPopup.dismiss()
                check_account_select.isChecked = false
                finish()
            })
    }

    override fun initView() {

        val mainBean: MainBean<*, *>? =
            intent?.getSerializableExtra(AppConstance.BUNDLE_WEB_VIEW) as? MainBean<*, *>

        if (mainBean != null) {
            val accessAction: AccessAction? = mainBean.type as? AccessAction
            if (accessAction == AccessAction.RESETPWD) {
                supportFragmentManager.beginTransaction()
                    .add(
                        R.id.frameLayout_access, AccessChangeFragment.newInstance("修改密码")
                    )
                    .commit()
            }
        } else if (BaseApplication.userToken().isNotEmpty() && BaseApplication.userInfo() != null) {
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MAIN)
                .navigation()
        } else {
            supportFragmentManager.beginTransaction()
                .add(
                    R.id.frameLayout_access, AccessAccountFragment.newInstance()
                )
                .commit()
            if (!SPStaticUtils.getBoolean(AppConstance.BUNDLE_USER_AGREE, (false))) {
                viewModel.configValue(arrayOf("user_register"))
            }
        }
    }


    override fun initViewMode() {

        viewModel.accessDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.userinfo?.let {
                if (it.mobile.isEmpty()) {
                    supportFragmentManager.beginTransaction()
                        .add(R.id.frameLayout_access, AccessWeChatFragment.newInstance())
                        .addToBackStack("")
                        .commit()
                } else {
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MAIN)
                        .navigation()
                    SPStaticUtils.put(AppConstance.BUNDLE_USER_INFO, JsonUtils.objectToString(it))
                }
                SPStaticUtils.put(AppConstance.BUNDLE_USER_TOKEN, it.token)
            }
        })
        viewModel.sendShortMessageDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "发送成功")
            if (accessAction == null)
                return@Observer
            val view: TextView = when (accessAction) {
                AccessAction.RESETPWD -> text_change_code
                AccessAction.REGISTER -> text_register_code
                AccessAction.MOBILE_LOGIN -> text_mobile_code
                else -> text_wechat_code
            }
            codeDownTime(view)
        })

        viewModel.resetpwdDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            onBackPressed()
            toast(response.response?.msg ?: "重置密码成功")
        })


        viewModel.configDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                webViewPopup.showPopupWindow()
                webViewPopup.setContent(it.user_register)
            }
        })
    }

    override fun onEventMainThread(eventBus: MainBean<*, *>) {
        super.onEventMainThread(eventBus)
        if (eventBus.type !is AuthResult)
            return
        if (eventBus.type == AuthResult.SUCCESS) {
            eventBus.data?.toString()?.let {
                isAgree = false
                viewModel.weChatLogin(it)
            }
        } else {
            toast(eventBus.type.desc)
        }
    }

    private var isAgree = false

    override fun onStop() {
        super.onStop()
        if (!isAgree) {
            this.finish()
        }
    }

    override fun onRestart() {
        super.onRestart()
        isAgree = true
    }

    fun onClickAccessBack(view: View) {
        when (view.id) {
            R.id.text_account_agree_user -> {
                isAgree = true
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.USER_AGREE, data = null)
                    )
                    .navigation()
            }
            R.id.text_account_agree_hide -> {
                isAgree = true
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.PRIVACY_AGREE, data = null)
                    )
                    .navigation()
            }
            R.id.text_mobile_agree_user -> {
                isAgree = true
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.USER_AGREE, data = null)
                    )
                    .navigation()
            }
            R.id.text_mobile_agree_hide -> {
                isAgree = true
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.PRIVACY_AGREE, data = null)
                    )
                    .navigation()
            }
            else -> {
                isAgree = false
                onBackPressed()
            }
        }
    }

    /**
     * 获取验证码倒计时
     * */
    private fun codeDownTime(view: TextView) {
        val disposable: Disposable =
            Flowable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    view.text = "剩余${60 - it}秒"
                }
                .doOnSubscribe {
                    view.isEnabled = false
                }
                .doOnComplete {
                    view.text = "获取验证码"
                    view.isEnabled = true
                }
                .subscribe()
        viewModel.dispose().add(disposable)
    }

    fun onClickAccessSelect(view: View) {
        when (view.id) {
            R.id.check_account_select -> {

            }
            R.id.check_mobile_select -> {
                check_account_select.isChecked = check_mobile_select.isChecked
            }
        }
    }

    fun onClickAccessNetwork(view: View) {
        isAgree = false
        when (view.id) {
            R.id.text_change_code -> {
                //获取验证码
                viewModel.sendShortMessage(
                    edit_change_phone.text.toString(), AccessAction.RESETPWD.desc
                )
                accessAction = AccessAction.RESETPWD
            }
            R.id.text_register_code -> {
                //获取验证码
                viewModel.sendShortMessage(
                    edit_register_phone.text.toString(), AccessAction.REGISTER.desc
                )
                accessAction = AccessAction.REGISTER
            }
            R.id.text_mobile_code -> {
                //获取验证码
                viewModel.sendShortMessage(
                    edit_mobile_phone.text.toString(), AccessAction.MOBILE_LOGIN.desc
                )
                accessAction = AccessAction.MOBILE_LOGIN
            }
            R.id.text_wechat_code -> {
                //获取验证码
                viewModel.sendShortMessage(
                    edit_wechat_phone.text.toString(), AccessAction.CHANGE_MOBILE.desc
                )
                accessAction = AccessAction.CHANGE_MOBILE
            }
            R.id.text_account_login -> {
                //密码登录
                if (check_account_select.isChecked) {
                    viewModel.login(
                        edit_account_phone.text.toString(),
                        edit_account_password.text.toString()
                    )
                } else {
                    toast("请勾选《用户协议》《隐私协议》")
                }
            }
            R.id.text_mobile_login_mobile -> {
                //验证码登录
                if (check_mobile_select.isChecked) {
                    viewModel.mobileLogin(
                        edit_mobile_phone.text.toString(),
                        edit_mobile_code.text.toString()
                    )
                } else {
                    toast("请勾选《用户协议》《隐私协议》")
                }
            }
            R.id.text_change_submit -> if (
                edit_change_password.text.toString() != edit_change_password_sure.text.toString()
            ) {
                toast("确认密码错误")
            } else {
                //忘记密码提交
                viewModel.resetpwd(
                    edit_change_phone.text.toString(),
                    edit_change_password.text.toString(),
                    edit_change_code.text.toString()
                )
            }
            R.id.text_register_register -> if (
                edit_register_password.text.toString() != edit_register_password_sure.text.toString()
            ) {
                toast("确认密码错误")
            } else {
                //立即注册
                viewModel.register(
                    edit_register_phone.text.toString(),
                    edit_register_nickname.text.toString(),
                    edit_register_password.text.toString(),
                    edit_register_code.text.toString()
                )
            }
            R.id.text_wechat_binding -> {
                //立即绑定
                viewModel.mobileBind(
                    edit_wechat_invitees_phone.text.toString(),
                    edit_wechat_invitees_name.text.toString(),
                    edit_wechat_nickname.text.toString(),
                    edit_wechat_card.text.toString(),
                    edit_wechat_phone.text.toString(),
                    edit_wechat_code.text.toString()
                )
            }
        }
    }

}